from django.db import models


# Create your models here.

class ProductLotRel(models.Model):
    """ProductType和LotNumber"""
    ProductType = models.CharField(max_length=256, null=False, blank=False)
    LotNumber = models.CharField(max_length=256, null=False, blank=False)

    class Meta:
        unique_together = ('ProductType', 'LotNumber')
        indexes = [
            models.Index(fields=['ProductType', 'LotNumber']),
        ]

    def __str__(self):
        return f'{self.ProductType} - {self.LotNumber}'


class ProductBaseInfo(models.Model):
    # 作为查询条件
    h_lot_number = models.CharField("生产批次号", max_length=256, default='')
    h_product_type = models.CharField("产品类型", max_length=256, default='')
    report_number = models.CharField("报告编号", max_length=256, default='')
    report_date = models.CharField("报告日期", max_length=256, default='')
    customer_name = models.CharField("客户名称", max_length=256, default='')
    order_number = models.CharField("订单号码", max_length=256, default='')
    # 作为查询条件
    production_lot_number = models.CharField("出货批次号", max_length=256, default='')

    specification_model = models.CharField("规格型号", max_length=256, default='')
    lot_quantity = models.CharField("批量", max_length=256, default='')
    direction_angle = models.CharField("方向角度", max_length=256, default='')
    feeding_angle = models.CharField("投料角度", max_length=256, default='')
    frequency_range = models.CharField("频率范围", max_length=256, default='')
    frequency_measurement_gap = models.CharField("频率测量间隙", max_length=256, default='')
    customer_material_number = models.CharField("出货产品料号", max_length=256, default='')
    product_size = models.CharField("产品尺寸", max_length=256, default='')

    appearance_sample_quantity = models.IntegerField("外观抽样数", default=0)
    ma_accept = models.IntegerField("Ma-ACC", default=0)
    ma_reject = models.IntegerField("Ma-REJ", default=0)

    frequency_diff_limit = models.CharField("△F规格值", max_length=256, default='')
    frequency_diff_control = models.CharField("△F管控值", max_length=256, default='')

    # Frequency offset degree
    frequency_offset_degree = models.IntegerField("频率偏移度", default=0)

    class Meta:
        verbose_name = "产品基本信息表"
        verbose_name_plural = "产品基本信息表"
        unique_together = ('h_lot_number', 'production_lot_number')

    def __str__(self):
        return self.h_lot_number


class ProductDownloadFile(models.Model):
    product_base_info = models.ForeignKey(ProductBaseInfo, on_delete=models.CASCADE, verbose_name="产品基本信息")
    file_path = models.CharField("Excel文件地址", max_length=512)
    created_at = models.DateTimeField("创建时间", auto_now_add=True)

    class Meta:
        verbose_name = "产品下载文件表"
        verbose_name_plural = "产品下载文件表"

    def __str__(self):
        return f"{self.product_base_info.h_lot_number} - {self.created_at.strftime('%Y-%m-%d %H:%M:%S')}"


class User(models.Model):
    ROLE_CHOICES = (
        ('admin', '管理员'),
        ('normal', '普通用户'),
    )

    username = models.CharField(
        '用户名',
        max_length=20,
        unique=True,
        error_messages={'unique': "该用户名已存在。"}
    )
    password = models.CharField('密码', max_length=30)
    role = models.CharField('角色', max_length=6, choices=ROLE_CHOICES, default='normal')

    def __str__(self):
        return self.username

    class Meta:
        verbose_name = '用户'
        verbose_name_plural = '用户'

    def save(self, *args, **kwargs):
        if len(self.username) < 3 or len(self.username) > 20:
            raise ValueError("用户名长度必须在3到20个字符之间")
        if len(self.password) < 5 or len(self.password) > 30:
            raise ValueError("密码长度必须在5到30个字符之间")
        super().save(*args, **kwargs)
